package operation;

import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

public class DelOperationJDBC implements IOperation{
    @Override
    public void work() throws SQLException {
        System.out.println("删除学生消息");
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource)dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/java110?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("zkzsa123");

        System.out.println("请输入你要删除的学号");
        Scanner sc = new Scanner(System.in);
        String studentId = sc.next();
        Connection connection = dataSource.getConnection();

        String sql1 ="select * from student";
        PreparedStatement statement1 = connection.prepareStatement(sql1);

        ResultSet rs = statement1.executeQuery();
        int i = 0;
        while(rs.next()){
            i++;
        }
        if(i == 0){
            System.out.println("学生表为空，不能删除");
            rs.close();
            statement1.close();
            connection.close();
            return;
        }

        String sql = "delete from student where studentId = ?";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setObject(1,studentId);
        int n = statement.executeUpdate();

        statement.close();
        connection.close();
        if(n > 0){
            System.out.println("删除成功");
            return;
        }
        System.out.println("删除失败");
    }
}
